//-----------------------------------------------------------------------------------------------
//										Selector
//-----------------------------------------------------------------------------------------------

var Selector_Instances = new Array();
var Selector_heightitem	= 22; 
var Selector_widthscroll = 15; // 10;
var Selector_heightscroll = 15; // 13;
var Selector_interval = 70;
var Selector_leftbutton	= false;
var Selector_porcmarker	= 2;
var Selector_inputtimer;
var Selector_inputkeytimelag = 200;

function WebSelector(id)
{
	// Atributos publicos
	this.value		      = ""; 
    this.description	  = "";
    
	this.width	 		  = 200; // en pixels
	this.size			  = 10;  // cantidad maxima de items
	this.getListFunction  = "";
	this.length           = 0;
	this.cssClass         = "";
	this.maxlength        = 0;
    
	// Atributos privados
	this.id				    = id;
	this.iswritten		    = false;
	this.enabled		    = true;
    this.active	            = true;
    this.minimumInputLength = 1;

    this.emptyText          = "Select...";
    this.multiple           = false;
    this.freeText           = false;
    
	// Funciones publicas
	this.getValue		  = Selector_GetValue;
	this.getDescription	  = Selector_GetDescription;
	this.setValue		  = Selector_SetValue;
	this.setDescription	  = Selector_SetDescription;	
	this.dispose		  = Selector_Dispose;
    this.clone            = Selector_Clone;
    
	this.disable 		  = Selector_Disable;
    this.enable			  = Selector_Enable;	    
    this.setActive		  = Selector_SetActive;	    
    this.setVisible		  = Selector_SetVisible;		
    this.clear		      = Selector_Clear;	
    
    this.show             = Selector_Show;
    this.showIn           = Selector_ShowIn;
    this.refresh          = Selector_Refresh;
    this.markControl      = Selector_MarkControl;
    
	// Eventos Personalizados
	this.evalOnSelect = Selector_EvalOnSelect;
	this.evalOnUnselect = Selector_EvalOnUnselect;	
	this.onSelect;
	this.onUnselect;
	
	Selector_Instances[id] = this;	
}

//Devuelve el valor que identifica al item seleccionado 
//Si el selector esta inactivo, devuelve directamente la descripcion 
function Selector_GetValue()
{
    if (this.iswritten) {
        var obj = document.getElementById(this.id);        
        var data = $(obj).select2('data');
        
        if (!data) {
            return "";
        }
        else if (this.multiple) {
            var ids = "";
            for (var i=0; i < data.length; i++) {
                ids += ((ids == "") ? "" : ",") + data[i].id;
            }
            return ids;
        }
        else {
            return data.id;
        }
    }
    else {
        return this.value;
    }
}

//Devuelve la descripcion del item seleccionado (el valor del input)
function Selector_GetDescription()
{
    if (this.iswritten) {
        var obj = document.getElementById(this.id);
        var data = $(obj).select2('data');
        
        if (!data) {
            return "";
        }
        else if (this.multiple) {
            var texts = "";
            for (var i = 0; i < data.length; i++) {
                texts += ((texts == "") ? "" : ",") + data[i].text;
            }
            return texts;
        }
        else {
            return data.text;
        }
    }
    else {
        return this.description;
    }    
}

//Establece el valor que identifica al item seleccionado 
function Selector_SetValue(value)
{
    if (this.iswritten) {
        var obj = document.getElementById(this.id);
        $(obj).select2('val', value);
    }
    else {
        this.value = value;
    }        
}

//Establece la descripcion del item seleccionado (el valor del input)
function Selector_SetDescription(desc)
{
    if (this.iswritten) {
        // not implemented!
    }
    else {
        this.description = desc;
    }       
}

//Saca el objeto de la pagina
function Selector_Dispose()
{
    if(this.iswritten) {
	    var divcont = document.getElementById("divcont" + this.id);
    	
	    if(divcont) {
	        if(divcont.parentElement)
	            divcont.parentElement.removeChild(divcont);
	        else
	            divcont.parentNode.removeChild(divcont);
	    }
    }

	delete Selector_Instances[this.id];
}

function Selector_Clone(newId)
{
    var newSelector = new WebSelector(newId);

	newSelector.width = this.width;
	newSelector.size = this.size;
	newSelector.getListFunction = this.getListFunction;
	newSelector.length = this.length;
	newSelector.cssClass = this.cssClass;
	
	newSelector.enabled = this.enabled;
	newSelector.active = this.active;
	
	newSelector.onSelect = this.onSelect;	
	newSelector.onUnselect = this.onUnselect;	
	
	newSelector.emptyText = this.emptyText;
	newSelector.multiple = this.multiple;
    
    return newSelector;
}

//Activo el Selector
function Selector_Enable()
{
    this.enabled = true;

    if (this.iswritten)
        this.refresh();
}

//Desactivo el Selector
function Selector_Disable()
{
    this.enabled = false;

    if (this.iswritten)
        this.refresh();
}

function Selector_SetActive(valor)
{
	this.active = valor;

    if(this.iswritten) {	
        // Registro el estado en la pagina
        var objActive =  document.getElementById(this.id + "_active");
        
        if(valor)
            objActive.value = "True";
        else
            objActive.value = "False";
    }
}

//Muestra/Oculta el control
function Selector_SetVisible(value)
{
    if(this.iswritten) {	
	    var cont = document.getElementById("divcont" + this.id);
	    ShowHideObject(cont, value);
	}
}

//Limpia el contenido del control
function Selector_Clear()
{
    Selector_ClearValue(this.id);
    Selector_ClearDescription(this.id);
}

function Selector_Fill(id, doc)
{
    var items = doc.getElementsByTagName('item'); // This remove all that ugly '#text' nodes
        
    var mSelector = Selector_Get(id);
    var data = { results: [] };

    for (var i = 0; i < items.length; i++) {
        idvalue = getNodeValue(items[i], 'id');
        value = getNodeValue(items[i], 'desc');

        data.results.push({ id: idvalue, text: value });
    }
    
    mSelector.query.callback(data);
}

function Selector_Show(containerId) {
    var container = document.getElementById(containerId);
    this.container = container;
    this.showIn(container);
}

function Selector_Refresh() {
    if (this.container) {
        this.showIn(this.container);
    }
}

function Selector_ShowIn(container) {
    var strenabled;
    var inputType;

    if (this.maxlength == 0) {
        maxlen = "";
    }
    else {
        maxlen = "maxlength=\"" + this.maxlength + "\"";
    }

    if (this.enabled) {
        strenabled = "";
    }
    else {
        strenabled = "readonly = \"readonly\"";
    }

    if (this.active) {
        inputType = "hidden";
    }
    else {
        inputType = "text";
    }

    // Dibujado del control
    var html = "";
    html += "<input id=\"" + this.id + "\" name=\"" + this.id + "\" " + maxlen + " value=\"" + this.description + "\" " + strenabled + " type=\"" + inputType + "\" class=\"selector\" />";
    html += "<input id=\"" + this.id + "_enabled\" name=\"" + this.id + "_enabled\" value=\"" + this.enabled.toString() + "\" type=\"hidden\" />";
    html += "<input id=\"" + this.id + "_active\" name=\"" + this.id + "_active\" value=\"" + this.active.toString() + "\" type=\"hidden\" />";

    // draw selector and apply select2 plugin
    var mSelector = this;

    if (mSelector.active) {
        $(container)
            .html(html)
            .find(".selector")
            .select2({
                placeholder: mSelector.emptyText,
                minimumInputLength: mSelector.minimumInputLength,
                minimumResultsForSearch: mSelector.size,
                multiple: mSelector.multiple,
                width: mSelector.width,
                allowClear: true,
                query: function(query) {
                    mSelector.query = query;
                    eval(mSelector.getListFunction + '(\"' + mSelector.id + "\",\"" + query.term + '\", ' + mSelector.size + ')');
                },
                initSelection: function(element, callback) {
                    if (mSelector.multiple) {
                        var data = [];
                        var values = mSelector.value.split(',');
                        var descriptions = mSelector.description.split(',');
                        $.each(values, function(index, value) {
                            data.push({ id: value, text: descriptions[index] });
                        });
                        callback(data);
                    } else {
                        callback({ id: mSelector.value, text: mSelector.description });
                    }
                },
                createSearchChoice: function(term, data) {
                    if (mSelector.freeText) {
                        if ($(data).filter(function() {
                            return this.text.localeCompare(term) === 0;
                        }).length === 0) {
                            return { id: term, text: term };
                        }
                    }
                }
            })
            .on("change", function() {
                mSelector.evalOnSelect();
            });

            $(container).on("select2-focus", function (e) {
                Selector_SetFocus(this.id, e);
            });
    }
    else {
        $(container).html(html);
    }

    this.iswritten = true;
}

function Selector_SetFocus(id, e)
{
    var mselector = Selector_Get(id);
    
    if( (mselector) && (mselector.enabled) ) {
        FocusManager.disposeFocus(e);
    }
}

function Selector_ClearValue(id)
{
    var objValue =  document.getElementById(id);
    
    if(objValue.value != "") {
        $(objValue).select2('val', '');

        // disparo el evento unselect
        var mSelector = Selector_Get(id);
        mSelector.evalOnUnselect();
    }
}

function Selector_ClearDescription(id)
{
    var objValue =  document.getElementById(id);
    
    if(objValue.value != "") {
        // not implemented!
    }
}


function Selector_MarkControl(ok) {
    if (ok)
        $("#cont_" + this.id).removeClass("error");
    else
        $("#cont_" + this.id).addClass("error");
}


//----------------Eventos Personalizados

function Selector_EvalOnSelect()
{
    eval(this.onSelect);
}

function Selector_EvalOnUnselect()
{
    eval(this.onUnselect);
}


//---------------Funciones Externas

//Esta funcion devuelve la lista correspondiente al id pasado como parametro
function Selector_Get(id)
{
    return (Selector_Instances[id]);
}


//---------------Funciones Genericas

function getNodeValue(obj, tag)
{
    return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}    

function ShowHideObject(obj, value)
{
	if (value)
		obj.style.visibility = "visible";
	else
		obj.style.visibility = "hidden";
}


